<script setup>
  import { onMounted, ref } from 'vue'
  import taskApi from '@/apis/task.js'
  // 待提货数据
  const pickupList = ref([])
  const nextPage = ref(1) //下一页
  const pages = ref(0) //总页数
  const isTriggered = ref(false) //默认是上拉未刷新状态
  onMounted(() => {
    getPickupList()
  })

  const getPickupList = async (page = 1, pageSize = 5) => {
    let { data } = await taskApi.tasklist(page, pageSize, 1)
    // 下拉刷新：将第一页数据覆盖pickupList.value
    if (page === 1) pickupList.value = []
    // 上拉分页
    // 将新页的数据追加到前面的数据中
    pickupList.value = [...pickupList.value, ...data.items]
    console.log(data.items)
    nextPage.value = ++data.page //拿到下一页
    pages.value = data.pages
  }
  // 定义上拉分页的触底函数
  function onScrollToLower() {
    // uni.utils.toast('触底触发')
    // 1.判断，如果nextPage.vlaue 大于pages.value 则不执行代码
    if (nextPage.value > pages.value) {
      return uni.utils.toast('已经没有数据')
    }
    // 1.重新调用getPicklist方法，传入nextPage的值
    getPickupList(nextPage.value)
  }
  // 定义下拉刷新的回调函数
  async function onRefresher() {
    // 1.打开下拉刷新的动画图
    isTriggered.value = true
    // 2.请求第一页数据
    const cpage = 1
    await getPickupList(cpage)
    // 3.关闭下拉刷新的动画图
    isTriggered.value = false
  }
</script>

<template>
  <scroll-view
    scroll-y
    refresher-enabled
    :refresher-triggered="isTriggered"
    @scrolltolower="onScrollToLower"
    @refresherrefresh="onRefresher"
    class="scroll-view"
  >
    <view class="scroll-view-wrapper">
      <view v-for="pickup in pickupList" :key="pickup.id" class="task-card">
        <navigator
          hover-class="none"
          :url="`/subpkg_task/detail/index?id=${pickup.id}`"
        >
          <view class="header">
            <text class="no">任务编号: {{ pickup.transportTaskId }}</text>
            <text class="status">已延迟</text>
          </view>
          <view class="body">
            <view class="timeline">
              <view class="line">{{ pickup.startAddress }}</view>
              <view class="line">{{ pickup.endAddress }}</view>
            </view>
          </view>
        </navigator>
        <view class="footer">
          <view class="label">提货时间</view>
          <view class="time">{{ pickup.planArrivalTime }}</view>
          <navigator
            v-if="pickup.enablePickUp"
            hover-class="none"
            url="/subpkg_task/pickup/index"
            class="action"
            >提货</navigator
          >
          <button
            v-if="!pickup.enablePickUp"
            class="action"
            disabled
            style="color: white"
          >
            提货
          </button>
        </view>
      </view>

      <view v-if="false" class="task-blank">无待提货物</view>
    </view>
  </scroll-view>
</template>

<style lang="scss" scoped>
  @import './styles.scss';
</style>
